const users = require('../models/users')
const studentWork = require('../models/studentWork')
const teamWork = require('../models/teamWork')
const course = require('../models/course')
const md5 = require('../utils/md5')
const formidable = require('formidable')
const node_xlsx = require('node-xlsx')
const fs = require('fs')

/****
 *
 * 用于创建管理员，平常可以关闭此接口
 *
 */
var test_register = async(ctx,next)=>{
    //判断是否存在
    let document = await users.findOne({userID:ctx.request.body.userID});
    if(document){
        return ctx.response.body = {stauts:'error',msg:'用户已存在',document};
    }

    var userID = ctx.request.body.userID;
    var password = md5(ctx.request.body.password);
    var userName = ctx.request.body.userName;
    var root = ctx.request.body.root;
    var major = ctx.request.body.major||"";
    var contact = ctx.request.body.contact||"";

    var userEntity = new users({
        userID:userID,
        password:password,
        userName:userName,
        root:root,
        major:major,
        contact:contact
    })

    userEntity.save(function(err,doc){
        if(err){
            console.log(err);
        }else{
            console.log(doc);
        }
    })
    password=null;
    return ctx.response.body = {stauts:'success',msg:'成功',userEntity};
}

/**
 *
 * 登录
 *
 */
var signin = async(ctx,next)=>{
    let signin_user = await users.findOne({userID:ctx.request.body.userID})
    if(signin_user){
        if(md5(ctx.request.body.password) === signin_user.password){
            signin_user.password = null;
            // ctx.session.user = signin_user;
            return ctx.response.body = {stauts:'success',msg:'成功',signin_user};
        }
        return ctx.response.body = {stauts:'error',msg:'密码错误',signin_user};
    }
    return ctx.response.body = {stauts:'error',msg:'用户不存在',signin_user};
}

/**
 *
 * 修改密码
 *
 */
var resetPW = async(ctx,next)=>{
    let signin_user = await users.findOne({userID:ctx.request.body.userID});
    if(signin_user){
        if(md5(ctx.request.body.password) === signin_user.password){
            let ID = signin_user._id;
            await users.findByIdAndUpdate(ID,{$set:{password:md5(ctx.request.body.newPassword)}},function(err,users){
                console.log(err);
            })
            signin_user.password = "";
            return ctx.response.body = {stauts:'success',msg:'成功',signin_user};
        }
        return ctx.response.body = {stauts:'error',msg:'密码错误'};
    }
    return ctx.response.body = {stauts:'error',msg:'用户未注册',signin_user};
}

/**
 *
 * 导入表注册
 *
 */
var Excel_register = async(ctx,next)=>{
    //excel处理和注册方法
    var stu1 = new Array();
    var ExcelParse = async function(newPath,itRoot){
        var stu = new Array();//用于存放已经注册的学生，防止重复注册
        var obj = node_xlsx.parse(newPath);
        var excelObj = obj[0].data;
        //统计学生信息
        var num=0;
        var userArray = new Array('userID','password','userName','course','major','contact');
        for(var i=1;i<excelObj.length;i++){
            var rdata = excelObj[i];
            if(!rdata[0]){
                continue;
            }
            var userData={};
            for(var j=0;j<rdata.length;j++){
                if(userArray[j]=='password'){
                    userData[userArray[j]]=md5(String(rdata[j]))
                    continue;
                }
                if(userArray[j]=='course'){
                  if(!rdata[j]==""){
                    userData[userArray[j]]=rdata[j].split(',');
                    continue;
                  }
                }
                userData[userArray[j]]=rdata[j];
            }
            //调试用
            // console.log(userData);
            //注册用
            var document = await users.findOne({userID:userData.userID});
            if(document){
                stu.push(userData);
            }else{
                var userEntity = new users({
                    root:itRoot,
                    userID:userData.userID,
                    password:userData.password,
                    userName:userData.userName,
                    course:userData.course,
                    major:userData.major,
                    contact:userData.contact
                })
                userEntity.save(function(err,doc){
                    if(err){
                        console.log(err);
                    }else{
                        console.log(doc);
                    }
                })
            }

        }
        console.log("成功");
        return stu;
    }
    var fileParse = async function(){
        var form = new formidable.IncomingForm();
            form.encoding = 'utf-8';
            form.uploadDir = './upload/excel/';
            form.keepExtensions = true;
            form.maxFieldsSize = 2*1024*1024;
            // console.log("0000");
        return new Promise((resolve,reject)=>{
            form.parse(ctx.req,async function(err,fields,files){
                if(err){
                    console.log(form);
                    console.log("err"+err);
                    return;
                }
                // console.log(fields.itRoot);
                console.log(files.filename.name);
                var fileName = files.filename.name;
                var itRoot = fields.itRoot;
                //文件名处理
                var nameArray = fileName.split('.');
                var type = nameArray[nameArray.length-1];
                var name = '';
                for(var i=0;i<nameArray.length-1;i++){
                    name = name+nameArray[i];
                }
                var date = new Date();
                var time = '_'+date.getFullYear()+'_'+(date.getMonth()+1)+'_'+date.getDate()+'_'+date.getHours()+'_'+date.getMinutes()+'_'+date.getSeconds();
                var avatarName = name+time+'.'+type;
                var newPath = form.uploadDir+avatarName;
                console.log(newPath);
                fs.renameSync(files.filename.path,newPath);
                console.log("重命名成功");
                //调用excel处理方法
                var stu = await ExcelParse(newPath,itRoot);
                resolve(stu);
            })
        })
    }
    stu1 = await fileParse();
    console.log(stu1.length)
    if(stu1.length==0){
        ctx.response.body = {stauts:'success',msg:'注册成功'};
    }else{
        ctx.response.body = {stauts:'warn',msg:'有部分用户已经注册',stu1};
    }
}

/**
 *
 * 用户表显示
 *
 */
var userShow=async(ctx,next)=>{
    let allUserArray= await users.find({root:ctx.request.body.root});
   // console.log(allUserArray);
    if(allUserArray){
            console.log("用户展示成功");
            return ctx.response.body = {stauts:'success',msg:'成功',allUserArray};
    }else{
        return ctx.response.body = {stauts:'error',msg:'暂无用户',allUserArray};
    }
}
/**
 * 
 * 管理员用增加单个用户，没有密码时默认123
 * userID,password,userName,root,major,contact(新用户的信息)
 * 
 */
var register = async(ctx,next)=>{
    //判断是否存在
    let document = await users.findOne({userID:ctx.request.body.userID});
    if(document){
        return ctx.response.body = {stauts:'error',msg:'用户已存在',document};
    }

    var userID = ctx.request.body.userID;
    var password = md5(ctx.request.body.password)||md5("123");
    var userName = ctx.request.body.userName;
    var root = ctx.request.body.root;
    var major = ctx.request.body.major||"";
    var contact = ctx.request.body.contact||"";

    var userEntity = new users({
        userID:userID,
        password:password,
        userName:userName,
        root:root,
        major:major,
        contact:contact
    })

    userEntity.save(function(err,doc){
        if(err){
            console.log(err);
        }else{
            console.log(doc);
        }
    })
    password=null;
    return ctx.response.body = {stauts:'success',msg:'成功',userEntity};
}
/**
 * 
 * 管理员用删除单个用户
 * ps:删除学生时删除包括其他表中该用户的信息
 * userID
 * 
 */
var del = async(ctx,next)=>{
    //判断是否存在
    let document = await users.findOne({userID:ctx.request.body.userID});
    if(document){
        await users.findByIdAndRemove(document._id);
        if(document.root==4){
            for(var i=0;i<document.course.length;i++){
                var cou = await course.findOne({course:document.course[i]})
                await course.findByIdAndUpdate(cou._id,{$pull:{student:document.userID}});
            }
            await studentWork.remove({studentID:document.userID})
            var team = await teamWork.find({teamMember:document.userID}) 
            for(var i=0;i<team.length;i++){
                await teamWork.findByIdAndUpdate(team._id,{$pull:{teamMember:document.userID}});
            }
        }
        return ctx.response.body = {stauts:'success',msg:'成功'};
    }else{
        return ctx.response.body = {stauts:'error',msg:'用户不存在'};
    }
    
}

module.exports = {
    'POST /users/test_register': test_register,
    'POST /users/signin': signin,
    'POST /users/resetPW': resetPW,
    'POST /users/Excel_register': Excel_register,
    'POST /users/userShow': userShow,
    'POST /users/register': register,
    'POST /users/del': del,
}
